<script setup>
import {onMounted, ref} from "vue";
import {cloud} from 'boot/weixin'
import {Dialog, Loading, date} from "quasar";
import {default_page_config, defult_checkpoint_list, saveGameConfig} from "src/utils/config";
import {useRouter} from "vue-router";
import {nanoid} from "nanoid";

const router = useRouter();

const project_list = ref([])
const project_templete = ref()
const show_project_dialog = ref(false)
const columns = ref([
  {
    name: "code",
    required: false,
    label: "邀请码",
    align: "left",
    field: "code",
    sortable: true,
  },
  {
    name: "title",
    required: false,
    label: "名称",
    align: "left",
    field: "title",
    sortable: true,
  },
  {
    name: "engine",
    required: false,
    label: "引擎",
    align: "left",
  },
  {
    name: "version",
    required: false,
    label: "版本",
    align: "left",
    field: "version",
    sortable: true,
  },
  {
    name: "beginDate",
    required: false,
    label: "开始日期",
    align: "left",
    field: "beginDate",
    sortable: true,
  },
  {
    name: "endDate",
    required: false,
    label: "结束日期",
    align: "left",
    field: "endDate",
    sortable: true,
  },
  {
    name: "enable",
    required: true,
    label: "启用",
    align: "center",
    field: "enable",
  },
  {
    name: "action",
    align: "left",
    label: "Action",
    field: "action",
    sortable: true
  },
])
const pagination = ref({
  rowsPerPage: 20,
})


function formatAppID(id) {
  const engine_name = {
    'wxa197cb55955c4f3f': '建字库',
    'wx7f4640fff2b3f7fa': '博物馆',
    'wx669785dcf46b4df6': '暗战'
  }
  return engine_name[id]
}

onMounted(async () => {
  await getProjectList()
})

async function getProjectList() {
  Loading.show({
    message: 'waiting...'
  })

  const db = cloud.database()
  const res = await db.collection('project')
      .field({
        code: true,
        title: true,
        appid: true,
        version: true,
        beginDate: true,
        endDate: true,
        enable: true,
      })
      .get()

  Loading.hide()

  project_list.value = res.data

}

async function getProject(data) {
  const db = cloud.database()
  const project = (await db.collection('project')
      .where({
        _id: data._id
      }).get()).data[0];

  console.log('project', project)

  // 重新对象化场地信息
  const config = {
    _id: project._id,
    version: project.version,
    code: project.code,
    memo: project.memo,
    title: project.title,
    appid: project.appid,
    beginDate: project.beginDate,
    endDate: project.endDate,
    page: JSON.parse(project.page),
    flow_list: project.flow_list,
  }

  Dialog.create({
    title: '提示',
    message: '本地数据将被覆盖，请再次输入邀请码：',
    prompt: {
      model: '',
      type: 'text' // optional
    },
    cancel: true,
    persistent: true
  }).onOk((data) => {
    if (data !== project.code) {
      return Dialog.create({
        title: '提示',
        message: '邀请码不一致，请再次确认'
      })
    }
    // 保存到本地
    saveGameConfig(config)

    // 导航到活动细节
    router.push({
      path: '/project_detail',
    })
  })
}

async function deleteProject(project) {
  console.log('delete', project)
  Dialog.create({
    title: '提示',
    message: '远程数据将被删除，请再次输入邀请码：',
    prompt: {
      model: '',
      type: 'text' // optional
    },
    cancel: true,
    persistent: true
  }).onOk(async (data) => {
    if (data !== project.code) {
      return Dialog.create({
        title: '提示',
        message: '邀请码不一致，请再次确认'
      })
    }

    // 删除数据
    const db = cloud.database()
    await db.collection('project')
        .doc(project._id).remove()
    await getProjectList()
  })

}

async function newProject() {
  const db = cloud.database()
  await db.collection('project').add({
    code: nanoid(),
    appid: 'wx7f4640fff2b3f7fa',
    beginDate: Date.now(),
    endDate: date.addToDate(new Date(), {year: 1}).getTime(),
    enable: true,
    title: '新游戏-' + date.formatDate(Date.now(), 'YYYY-MM-DD'),
    memo: '新游戏-' + date.formatDate(Date.now(), 'YYYY-MM-DD'),
    version: process.env.version,
    checkpoint_list: JSON.stringify(defult_checkpoint_list),
    flow_list: defult_checkpoint_list,
    page: JSON.stringify(default_page_config)
  })
  await getProjectList()
}

</script>

<template>
  <q-page class="q-pa-md">
    <q-table title="项目管理" :rows="project_list" :columns="columns" row-key="" v-model:pagination="pagination">

      <template v-slot:top-right>
        <q-btn @click="newProject" size="md" color="primary" class="q-mr-xs" label="新建项目"/>
      </template>

      <template v-slot:body-cell-enable="props">
        <q-td :props="props">
          <q-toggle v-model="props.row.enable"/>
        </q-td>
      </template>

      <template v-slot:body-cell-engine="props">
        <q-td :props="props">
          <div>{{ formatAppID(props.row.appid) }}</div>
        </q-td>
      </template>

      <template v-slot:body-cell-beginDate="props">
        <q-td :props="props">
          <div>{{ $moment(props.row.beginDate).format('YYYY年MM月DD日') }}</div>
        </q-td>
      </template>

      <template v-slot:body-cell-endDate="props">
        <q-td :props="props">
          <div>{{ $moment(props.row.endDate).format('YYYY年MM月DD日') }}</div>
        </q-td>
      </template>

      <template v-slot:body-cell-action="props">
        <q-td :props="props">
          <div class="q-gutter-sm">
            <q-btn dense outline size="sm" color="green" icon="download_for_offline"
                   @click="getProject(props.row)"/>
            <q-btn dense outline size="sm" color="red" icon="delete" @click="deleteProject(props.row)"/>
          </div>
        </q-td>
      </template>
    </q-table>
    <q-dialog v-model="show_project_dialog">
      <q-card bordered class="my-card">
        <q-card-section class="q-pt-md full-width">
          基础框架:
          <q-select v-model="project_templete" :options="project_list" option-label="memo" option-value="_id"
                    label="Standard"/>
        </q-card-section>
      </q-card>
    </q-dialog>
  </q-page>

</template>

<style scoped lang="sass">
.my-card
  width: 100%
  max-width: 900px
</style>
